<template>
  <div class="goods-add-container">
    <el-row :gutter="20">
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header"
               class="clearfix">
            <span style="font-size:18px;font-weight:900;">基础信息</span>
          </div>
          <div>
            <div>展示图</div>
            <div style="margin-top:10px">
              <el-upload class="upload-demo"
                         :on-success="headUploadSuccess"
                         :on-remove="headUploadSuccess"
                         :action="upload_action"
                         :show-file-list="false">
                <img v-if="head"
                     :src="head"
                     class="avatar">
                <i v-else
                   class="el-icon-plus avatar-uploader-icon"></i>

                <div class="el-upload__tip"
                     slot="tip">请上传宽高比1/1正方形jpg,png,jpeg照片，且不超过500kb</div>
              </el-upload>
            </div>

            <div style="margin-top:20px">商品图片和视频（{{img.length}}/9）</div>
            <div style="margin-top:10px">
              <el-upload :action="upload_action"
                         :data="{store:'product'}"
                         :on-success="imgUploadSuccess"
                         :on-remove="imgRemoveSuccess"
                         list-type="picture-card"
                         :file-list="img">
                <i class="el-icon-plus"></i>
              </el-upload>
            </div>
            <div class="el-upload__tip">最多上传9个素材，其中最多上传1个视频（mp4格式），视频时长不超过60秒，视频大小不超过200M。视频将默认展示在图片之前，拖拽图片可进行排序，单张图片需限制在10M以内。</div>

            <el-row :gutter="30"
                    style="margin-top:20px">
              <el-col :span="12">
                <div>商品标题</div>
                <div style="margin-top:10px">
                  <el-input v-model="title"
                            placeholder="请输入内容"
                            maxlength="40"
                            show-word-limit></el-input>
                </div>
              </el-col>
              <el-col :span="12">
                <div>商品编码</div>
                <div style="margin-top:10px">
                  <el-input v-model="code"
                            placeholder="请输入内容"></el-input>
                </div>
              </el-col>
              <el-col :span="12"
                      style="margin-top:20px">
                <div>所属分组</div>
                <div style="margin-top:10px">
                  <el-select v-model="category_id"
                             placeholder="请选择"
                             multiple>
                    <el-option v-for="item in category_list"
                               :key="item.id"
                               :label="item.title"
                               :value="item.id+''">
                    </el-option>
                  </el-select>
                </div>
              </el-col>
              <el-col :span="12"
                      style="margin-top:20px">
                <div>商品描述(选填)</div>
                <div style="margin-top:10px">
                  <el-input v-model="describe"
                            placeholder="请输入内容"
                            maxlength="20"
                            show-word-limit></el-input>
                </div>
              </el-col>
            </el-row>
          </div>
        </el-card>

        <el-card class="box-card"
                 style="margin-top:20px">
          <div slot="header"
               class="clearfix">
            <span style="font-size:18px;font-weight:900;">商品详情</span>
          </div>
          <div>
            <el-input type="textarea"
                      :rows="8"
                      placeholder="请输入内容"
                      v-model="detail_text"
                      maxlength="2000"
                      show-word-limit>
            </el-input>
            <div style="margin-top:20px">
              <el-upload :action="upload_action"
                         :data="{store:'product'}"
                         :on-success="detailUploadSuccess"
                         :on-remove="detailRemoveSuccess"
                         :file-list="detail_img"
                         list-type="picture-card">
                <i class="el-icon-plus"></i>
              </el-upload>
            </div>
            <div style="margin-top:10px;color:#999;font-size:14px">最多上传20个素材，拖拽可进行排序，单张图片需限制在10M以内</div>
          </div>
        </el-card>

        <el-card class="box-card"
                 style="margin-top:20px">
          <div slot="header"
               class="clearfix">
            <span style="font-size:18px;font-weight:900;">商品参数</span>
          </div>
          <div style="margin-top:20px">
            <el-form ref="form"
                     label-width="80px">
              <el-form-item label="风格">
                <el-select placeholder="请选择风格"
                           v-model="mode">
                  <el-option :label="item.title"
                             :value="item.id+''"
                             v-for="item in mode_list"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="元素">
                <el-select placeholder="请选择元素"
                           v-model="popular">
                  <el-option :label="item.title"
                             :value="item.id+''"
                             v-for="item in popular_list"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="材料">
                <el-select placeholder="请选择材料"
                           v-model="material">
                  <el-option :label="item.title"
                             :value="item.id+''"
                             v-for="item in material_list"></el-option>
                </el-select>
              </el-form-item>
            </el-form>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="box-card">
          <div slot="header"
               class="clearfix">
            <span style="font-size:18px;font-weight:900;">规格参数</span>
          </div>
          <div>
            <div class="goods-attr-item"
                 v-for="(item,index) in goods_item">
              <div class="goods-item-row">
                <div class="goods-item-row-left">
                  <div class="goods-item-title">
                    属性{{index+1}}
                  </div>
                  <div class="goods-item-input">
                    <el-input v-model="item.title"
                              placeholder="请输入内容"></el-input>
                  </div>
                  <div class="goods-item-check">
                    <el-radio v-model="item.img"
                              :label="1">配图</el-radio>
                  </div>
                </div>
                <div class="goods-item-row-right">
                  删除属性
                </div>
              </div>
              <div class="goods-content-row"
                   v-for="(item1,index1) in item.with_item">
                <div class="content-row-left">
                  <el-input v-model="item1.title"
                            placeholder="请输入内容"
                            style="width:300px"
                            @blur="changeGoodsItem(index)"></el-input>
                </div>
                <div class="content-row-right">
                  <el-button icon="el-icon-picture-outline"
                             circle
                             v-if="item.img==1"></el-button>
                  <el-button icon="el-icon-delete"
                             circle
                             @click="delGoodsIitem(index,index1)"
                             v-if="item.with_item.length>1"></el-button>
                </div>
              </div>
              <div class="addTxt"
                   @click="addGoodsIitem(index)"><i class="el-icon-circle-plus-outline"></i>添加子属性
              </div>
            </div>
            <div>
              <el-button @click="addGoods">新增参数</el-button>
            </div>

          </div>
        </el-card>

        <el-card class="box-card"
                 style="margin-top:20px">
          <div slot="header"
               class="clearfix">
            <span style="font-size:18px;font-weight:900;">规格售价与库存</span>
          </div>
          <div>
            <el-row :gutter="20">
              <el-col :span="6">
                售卖价
              </el-col>
              <el-col :span="6">
                市场价
              </el-col>
              <el-col :span="6">
                库存
              </el-col>
              <el-col :span="6">
                状态
              </el-col>
            </el-row>

            <div v-for="item in price_zuhe"
                 style="margin-top:20px;margin-bottom:20px">
              <div style="margin-top:20px;margin-bottom:10px"><span v-for="i in item.title">{{i}}</span></div>
              <el-row :gutter="20">
                <el-col :span="6">
                  <el-input placeholder="请输入内容"
                            v-model="item.price"></el-input>
                </el-col>
                <el-col :span="6">
                  <el-input placeholder="请输入内容"
                            v-model="item.market_price"></el-input>
                </el-col>
                <el-col :span="6">
                  <el-input placeholder="请输入内容"
                            v-model="item.stock"></el-input>
                </el-col>
                <el-col :span="6">
                  <el-select v-model="item.status"
                             placeholder="请选择">
                    <el-option :key="1"
                               label="上架"
                               :value="1">
                    </el-option>
                    <el-option :key="2"
                               label="下架"
                               :value="0">
                    </el-option>
                  </el-select>
                </el-col>
              </el-row>
            </div>
          </div>
        </el-card>

        <el-button type="danger"
                   style="margin-top:20px"
                   @click="submitPost()">{{id?"保存修改":"新增商品"}}</el-button>
      </el-col>
    </el-row>
  </div>
</template>
    
<script>
import { addData, getModeList, getRead, getPopularList, getMaterialList, editData } from "@/api/product";
import { getList as getCategoryList } from "@/api/productCategory";

export default {
  data () {
    return {
      id: null,
      head: '',
      img: [],
      title: '',
      describe: '',
      code: '',
      category_id: [],
      upload_action: process.env.VUE_APP_UPLOAD_ACTION,
      detail_text: '',
      detail_img: [],
      mode_list: [],
      material_list: [],
      popular_list: [],
      category_list: [],
      mode: null,
      material: null,
      popular: null,
      goods_item: [
        {
          title: '',
          img: 1,
          with_item: [{
            title: ""
          }]
        }
      ],
      price_zuhe: [],
    }
  },
  created () {
    if (this.$route.query.id) {
      this.id = this.$route.query.id;
      this.fetchData(this.id)
    }
    this.fetchModeData()
    this.fetchPopularData()
    this.fetchMaterialData()
    this.fetchCategoryData()
  },
  methods: {
    fetchData (id) {
      getRead({ id: id }).then(response => {
        let data = response.data
        this.category_id = data.category_id
        this.code = data.code
        this.title = data.title
        this.material = data.material
        this.mode = data.mode
        this.popular = data.popular
        this.describe = data.describe
        this.detail_text = data.detail_text
        this.goods_item = data.goods_item
        this.price_zuhe = data.price_zuhe
        data.img.forEach(element => {
          this.img.push({
            "url": element
          })
        });


        data.detail_img.forEach(element => {
          this.detail_img.push({
            "url": element
          })
        });
        this.head = data.head
      })
    },
    fetchModeData () {
      getModeList().then(response => {
        this.mode_list = response.data
      })
    },
    fetchPopularData () {
      getPopularList().then(response => {
        this.popular_list = response.data
      })
    },
    fetchMaterialData () {
      getMaterialList().then(response => {
        this.material_list = response.data
      })
    },

    fetchCategoryData () {
      getCategoryList().then(response => {
        this.category_list = response.data.data
      })
    },

    //提交数据
    submitPost () {
      if (this.title == '') {
        this.$message.error('请输入商品的标题');
        return false;
      }
      if (this.img.length == 0) {
        this.$message.error('请上传至少一个商品图片和视频');
        return false;
      }
      if (this.price_zuhe.length == 0) {
        this.$message.error('请输入至少一个规格信息');
        return false;
      }
      let data = {
        head: this.head,
        code: this.code,
        category_id: this.category_id,
        img: this.img,
        title: this.title,
        describe: this.describe,
        detail_text: this.detail_text,
        detail_img: this.detail_img,
        price_zuhe: this.price_zuhe,
        goods_item: this.goods_item,
        material: this.material,
        popular: this.popular,
        mode: this.mode,
      }
      if (this.id) {
        data.id = this.id
        editData(data).then(response => {
        })
      } else {
        addData(data).then(response => {
        })
      }
    },
    //输入框改变
    changeGoodsItem () {
      setTimeout(() => {
        this.doExchange(1)
      }, 500);
    },
    /**
     * 上传头图
     */
    headUploadSuccess (response, file, fileList) {
      this.head = response.data.data;
    },
    headRemoveSuccess (file, fileList) {
      this.head = '';
    },
    /**
     * 上传详情图片
     */
    detailUploadSuccess (response, file, fileList) {
      this.detail_img.push(response.data.data)
    },
    detailRemoveSuccess (file, fileList) {
      this.img.forEach((element, index) => {
        if (element == file.response.data.data) {
          this.detail_img.splice(index, 1)
        }
      });
    },
    /**
     * 上传图片
     */
    imgUploadSuccess (response, file, fileList) {
      this.img.push({ "url": response.data.data })
    },
    imgRemoveSuccess (file, fileList) {
      this.img.forEach((element, index) => {
        if (element == file.response.data.data) {
          this.img.splice(index, 1)
        }
      });
    },
    addGoods () {
      this.goods_item.push(
        {
          title: '自定义参数',
          img: 0,
          item: [{
            title: ""
          }]
        })
    },
    addGoodsIitem (index) {
      this.goods_item[index].with_item.push({
        title: ''
      })
    },
    delGoodsIitem (index, index1) {
      this.goods_item[index].with_item.splice(index1, 1)
      setTimeout(() => {
        this.doExchange(3)
      }, 500);
    },

    doExchange (type = 1) {
      let arr = []
      this.goods_item.forEach(element => {
        let a = [];
        element.with_item.forEach(element1 => {
          if (element1.title) {
            a.push(element1.title)
          }
        });
        arr.push(a)
      });
      var sarr = [[]];
      for (var i = 0; i < arr.length; i++) {
        var tarr = [];
        for (var j = 0; j < sarr.length; j++)
          for (var k = 0; k < arr[i].length; k++)
            tarr.push(sarr[j].concat(arr[i][k]));
        sarr = tarr;
      }
      if (type == 1) {
        let data1 = []
        this.price_zuhe.forEach((element, index) => {
          sarr.forEach(element1 => {
            if (element.title == element1.join(',')) {
              data1.push(element)
            }
          })
        })
        this.price_zuhe = data1

        sarr.forEach((element, index) => {
          let a = true
          data1.forEach((element1, index1) => {
            if (element1.title == element.join(',')) {
              a = false
            }
          });

          if (a) {
            this.price_zuhe.push({
              "title": element.join(','),
              "market_price": '',
              "price": '',
              "stock": '',
              "status": 1,
            })
          }
        });

      } else {

        let arr2 = [];
        sarr.forEach(element => {
          arr2.push(element.join(','));
        })
        //删除一个子项目
        this.price_zuhe.forEach((element, index) => {
          if (arr2.indexOf(element.title) == -1) {
            this.price_zuhe.splice(index, 1)
          }
        });
      }
    }
  }
}
</script>
    
<style lang="scss" scoped>
.goods-add-container {
  font-family: PingFang SC;
  padding: 30px;
  margin: 0 auto;
  .goods-attr-item {
    padding: 20px;
    background-color: #f5f5f5;
    border-radius: 10px;
    margin-bottom: 20px;
    .goods-item-row {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .goods-item-row-left {
        display: flex;
        justify-content: flex-start;
        align-items: center;
        height: 40px;
        .goods-item-title {
          margin-right: 20px;
          font-weight: 400;
        }
        .goods-item-check {
          margin-left: 20px;
        }
      }
      .goods-item-row-right {
        color: #0b4c8d;
        cursor: pointer;
      }
    }
    .goods-content-row {
      margin-top: 10px;
      padding-left: 60px;
      display: flex;
      align-items: center;
      .content-row-right {
        padding-left: 20px;
        font-size: 30px;
      }
    }
    .addTxt {
      color: #0b4c8d;
      display: flex;
      align-items: center;
      padding: 20px;
      padding-left: 60px;
      cursor: pointer;
    }
  }
}
</style>